<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="addPermission(1, '0')"
          >添加权限</el-button>
        </div>

        <el-table row-key="id" :data="permissionList" border>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button
                v-if="scope.row.type === 1"
                type="text"
                @click="addPermission(2, scope.row.id)"
              >添加</el-button>
              <el-button
                type="text"
                @click="editPerHander(scope.row.id)"
              >编辑</el-button>
              <el-button type="text" @click="delPerHander(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog
          :title="isEdit ? '编辑权限' : '新增权限'"
          :visible="showDialog"
          center
          @close="btnCancel"
        >
          <!-- 表单 -->
          <el-form
            ref="perForm"
            :model="formData"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width: 90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button
                size="small"
                type="primary"
                @click="addPer"
              >确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  getPermissionList,
  addPermission,
  getPermissionDetail,
  updatePermission,
  delPermission
} from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 自定义验证函数
    // 同级不允许同名称存在还
    const validName = (rule, value, callback) => {
      // 新增权限 --> 找到同级兄弟节点 --> 找到name --> 输入的值与找到的名称对比
      let existList = this.originList.filter(item => item.pid === this.formData.pid)
      // 编辑权限 --> 找到同级兄弟节点并排除自己
      if (this.isEdit) {
        existList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existList.map(item => item.name.trim()).includes(value) ? callback(new Error(`权限名称${value}已存在`)) : callback()
    }

    // 权限标识在整个模块都不允许重复
    const validCode = (rule, value, callback) => {
      // 新增权限 --> 找到全部的权限标识 --> 输入的值与权限标识进行对比
      let existCodeList = this.originList
      // 编辑时,排除本身
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      // 遍历出code放到一个数组里
      existCodeList.map(item => item.code)
        .includes(value) ? callback(new Error(`权限标识${value}已存在`)) : callback()
    }

    return {
      permissionList: [], // 权限管理列表数据
      showDialog: false, // 是否显示弹层
      isEdit: false, // 编辑/新增权限状态
      originList: [], // 精简后的数据
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用获取权限列表的方法
    this.getPermissionList()
  },
  methods: {
    // 删除权限
    async delPerHander(id) {
      const confirmRes = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击取消
      if (confirmRes === 'cancel') return this.$message('取消了删除')
      // 点击确定 --> 调用接口 --> 提示用户 --> 刷新列表
      const res = await delPermission(id)
      this.$message.success(res.message)
      this.getPermissionList()
    },

    // 添加权限
    async addPerHandler() {
      // 验证通过 --> 发请求 --> 提示用户 --> 关闭弹框 --> 状态为false --> 刷新列表
      const res = await addPermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.isEdit = false
      this.getPermissionList()
    },

    // 编辑权限数据回显
    async editPerHander(id) {
      // 调用API,获取数据 --> 展示弹框 --> 状态为true
      const res = await getPermissionDetail(id)
      this.formData = res.data
      this.showDialog = true
      this.isEdit = true
    },

    // 编辑权限
    async editPermission() {
      const res = await updatePermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()
    },

    // 确定 --> 添加权限
    addPer() {
      this.$refs.perForm.validate(async(valid) => {
        // 验证不通过
        if (!valid) return
        this.isEdit ? this.editPermission() : this.addPerHandler()
      })
    },

    // 显示新增权限弹框
    addPermission(type, pid) {
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = pid
    },

    // 隐藏新增权限弹框
    btnCancel() {
      // 点击取消 --> 清空输入内容/清除验证规则
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },

    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      // 自定义验证规则使用简化的数据
      this.originList = res.data.map(item => ({
        id: item.id,
        pid: item.pid,
        name: item.name,
        code: item.code
      }))
      this.permissionList = tranListToTreeData(res.data)
    }
  }
}
</script>

<style lang="scss" scoped></style>
